package com.imddy.spbatch001.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class JpaPageUtils {
    private static final Logger log = LoggerFactory.getLogger(JpaPageUtils.class);
    private static Integer defaultPageSize = 10;

    public static <T> Page<T> listToPage(List<T> list, int pageNum) {
        PageRequest pageable = PageRequest.of(pageNum - 1, defaultPageSize);
        return getPage(list, pageable);
    }

    public static <T> Page<T> listToPage(List<T> list, int pageNum, int pageSize) {
        PageRequest pageable = PageRequest.of(pageNum - 1, pageSize);
        return getPage(list, pageable);
    }

    public static <T> Page<T> getPage(List<T> list) {
        PageRequest pageable = PageRequest.of(0, defaultPageSize);
        return getPage(list, pageable);
    }

    public static <T> Page<T> getPage(List<T> list, Pageable pageable) {
        // 第n页起始值
        int pageStart = pageable.getPageNumber() * pageable.getPageSize();
        // 第n页期望结尾值
        int expectPageEnd = pageStart + pageable.getPageSize() - 1;
        return Optional.of(list.size()).filter(size -> size >= pageStart)
                .map(size -> getRealSubList(pageStart, expectPageEnd, list, pageable))
                .orElseGet(() -> getEmptySubList(list, pageable));
    }

    private static <T> PageImpl<T> getRealSubList(int pageStart, int expectPageEnd, List<T> list, Pageable pageable) {
        int realPageEnd = (list.size() > expectPageEnd) ? expectPageEnd + 1	: list.size();
        return new PageImpl<>(list.subList(pageStart, realPageEnd), pageable, list.size());
    }

    private static <T> PageImpl<T> getEmptySubList(List<T> list, Pageable pageable) {
        return new PageImpl<>(new ArrayList(), pageable, list.size());
    }

}
